package com.bookmanagement.service.impl;


import com.bookmanagement.VO.BookBasicVO;
import com.bookmanagement.constant.RedisConstant;
import com.bookmanagement.entity.Book;
import com.bookmanagement.mapper.BookMapper;
import com.bookmanagement.result.PageResult;
import com.bookmanagement.service.CollectionService;
import com.bookmanagement.utils.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * @author skyjay
 */
@Service
public class CollectionServiceImpl implements CollectionService {

    @Autowired
    private BookMapper bookMapper;


    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public PageResult getCollection() {
        String currentId = BaseContext.getCurrentId();
        String key = RedisConstant.USER_COLLECTION+currentId;
        Set<String> bookIds = stringRedisTemplate.opsForSet().members(key);
        if(bookIds==null|| bookIds.isEmpty()){
            return PageResult.builder()
                    .total(0)
                    .records(Collections.emptyList())
                    .build();
        }
        ArrayList<Long> bookIdAsList = new ArrayList<>();
        bookIds.forEach(bookId->{
            Long id = Long.parseLong(bookId);
            bookIdAsList.add( id);
        });
        List<Book> books = bookMapper.getBatchByID(bookIdAsList);
        List<BookBasicVO> bookBasicVOS = books.stream().map(book -> {
            return BookBasicVO.builder()
                    .categoryId(book.getCategoryId())
                    .stock(book.getStock())
                    .title(book.getTitle())
                    .author(book.getAuthor())
                    .build();
        }).collect(Collectors.toList());
        return PageResult.builder()
                .total(bookBasicVOS.size())
                .records(bookBasicVOS)
                .build();
    }

    @Override
    @Transactional
    public void isCollection(Integer bookId) {
        String currentId = BaseContext.getCurrentId();
        String key = RedisConstant.USER_COLLECTION+currentId;
        Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, bookId.toString());
        if(Boolean.TRUE.equals(isMember)){
            stringRedisTemplate.opsForSet().remove(key, bookId.toString());
            bookMapper.cancelCollection(bookId);
        }
        else{
            stringRedisTemplate.opsForSet().add(key, bookId.toString());
            bookMapper.addCollection(bookId);
        }
    }
}
